import 'dart:io';

import 'package:chewie/chewie.dart';
import 'package:edu_assistant/util/custom_cache_manager.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:video_player/video_player.dart';

class VideoPlayerScreen extends StatefulWidget {
  final String url;
  final String title;
  const VideoPlayerScreen({super.key, required this.url, required this.title});

  @override
  State<VideoPlayerScreen> createState() => _VideoPlayerScreenState();
}

class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
  String showTitle = '';
  late VideoPlayerController _videoPlayerController;
  late ChewieController _chewieController;
  final CacheManager cacheManager = CustomCacheManager.instance;
  @override
  void initState() {
    super.initState();
    showTitle = widget.title;
    _videoPlayerController =
        VideoPlayerController.networkUrl(Uri.parse(widget.url));
    // _initializePlayer();
    _initVideo();
  }

  //版本二
  void _initVideo() async {
    final file = await DefaultCacheManager().getSingleFile(widget.url);
    _videoPlayerController = VideoPlayerController.file(file)
      ..initialize().then(
        (value) {
          setState(() {});
        },
      );
    _chewieController = ChewieController(
      videoPlayerController: _videoPlayerController,
      aspectRatio: 16 / 9,
      autoPlay: true,
      looping: true,
      autoInitialize: true,
    );
  }

  @override
  void dispose() {
    _videoPlayerController.dispose();
    _chewieController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(showTitle),
      ),
      body: Center(
        child: _videoPlayerController.value.isInitialized
            ? Chewie(
                controller: _chewieController,
              )
            : CircularProgressIndicator(),
      ),
    );
  }
}
